package org.wheres2;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.wheres2.core.ServiceClient;
import org.wheres2.core.contactlist.ContactManager;
import org.wheres2.eventmanager.ConnectionErrorManager;
import org.wheres2.eventmanager.PositionManager;
import org.wheres2.utils.MessageMod;
import org.wheres2.utils.MySimpleAdapter;

import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * La classe implementa l'activity ContactInteraction che vusualizza un contatto ed i pulsanti per 
 * le possibili interazioni
 * 
 * @author 
 *
 */
public class ContactInteraction extends Activity implements PositionManager,ConnectionErrorManager {
	
		private boolean boundToService;
		private ServiceClient client;
		private Intent serviceIntent;
		private TextView name;
		private TextView user;
		private TextView myPosText;
		private TextView contactPosText;
		private Location location;
		private Button sendPos;
		private Button reqPos;
		private ImageButton locateButton;
		private Intent intent;
		private ContactManager contact;
		private boolean isOnScreen = false;
		
	private ServiceConnection communicatorConnection = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			client = ((ServiceClient.ServiceClientBinder)service).getService();
			location = client.getLocation();
			client.addPositionListener(ContactInteraction.this);
			client.addConnectionErrorListener(ContactInteraction.this);
			buildActivity();
			boundToService = true;			
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			client = null;
			boundToService = false;
		}	
	};


	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		intent = getIntent();
		
		name = (TextView) findViewById(R.id.contactNameBold);
		user = (TextView) findViewById(R.id.contactUser);
		myPosText =(TextView) findViewById(R.id.myContactInteractionPosition);
		contactPosText = (TextView) findViewById(R.id.contactContactInteractionPosition);
		contactPosText.setVisibility(View.INVISIBLE);
		sendPos = (Button) findViewById(R.id.sendPosButton);
		reqPos = (Button) findViewById(R.id.requestPosButton);
		locateButton = (ImageButton) findViewById(R.id.locateButton);
		sendPos.setEnabled(false);
		reqPos.setEnabled(false);
		locateButton.setEnabled(false);		
		
	}
	
	
	@Override
	protected void onResume() {
		if(!this.boundToService){
			serviceIntent = new Intent(ContactInteraction.this, ServiceClient.class);
			bindService(serviceIntent, communicatorConnection, Context.BIND_DEBUG_UNBIND);
		}
		this.isOnScreen = true;
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		if (this.boundToService){
			unbindService(communicatorConnection);
			this.boundToService = false;
		}
		this.isOnScreen = false;
		super.onPause();
	}
	
	/**
	 * 
	 * Costrusce l'activity a binding avvenuto
	 * 
	 */
	private void buildActivity(){
		
		String username = intent.getStringExtra(MySimpleAdapter.EXTRA_USER);
		String nome = intent.getStringExtra(MySimpleAdapter.EXTRA_NAME);
		String myLocation = getResources().getString(R.string.MyLocation);
		String otherLocation = getResources().getString(R.string.OtherLocation);
		name.setText(nome);
		user.setText(username);
		contact = this.client.getContact(username);
		SimpleDateFormat sdf;
		Date d;
		
		this.client.removeAllNotifications(username);
		if(intent.getIntExtra(MySimpleAdapter.EXTRA_GROUP, 1) == 0){
			sendPos.setEnabled(true);
			reqPos.setEnabled(true);		
			locateButton.setEnabled(true);
		}
		
		if(client.isGPSProviderEnabled() || client.isNetProviderEnabled()){
			if(!client.isGPSProviderEnabled())
				Toast.makeText(this, R.string.NoGpsProviderToast, Toast.LENGTH_LONG).show();
			
			if(!client.isNetProviderEnabled())
				Toast.makeText(this, R.string.NoNetProviderToast, Toast.LENGTH_LONG).show();
			
			if(location != null){
				d = new Date(location.getTime());
				sdf = (SimpleDateFormat)SimpleDateFormat.getDateTimeInstance();			
				String date = sdf.format(d);
				myPosText.setText(myLocation + 
								"\nLat: " + location.getLatitude() + " Long:" + location.getLongitude() +
								"\nPrec: " + location.getAccuracy() + " Da: " + location.getProvider() + 
								"\nRilevata il: " + date);
			}else{			
				String locationWaiting = getResources().getString(R.string.LocationWaiting);
				myPosText.setText(myLocation + "\n" + locationWaiting);
			}	
			
			if(this.contact.getLocation() != null){
				contactPosText.setVisibility(View.VISIBLE);
				d = new Date(this.contact.getLocation().getTime());
				sdf = (SimpleDateFormat)SimpleDateFormat.getDateTimeInstance();			
				String date = sdf.format(d);
				contactPosText.setText(otherLocation + 
								"\nLat: " + this.contact.getLocation().getLatitude() + 
								" Long:" + this.contact.getLocation().getLongitude() +
								"\nPrec: " + this.contact.getLocation().getAccuracy() + 
								"\nInviata il: " + date);
			}else{			
				contactPosText.setVisibility(View.INVISIBLE);
			}
		}
			
	}
	
	/**
	 * 
	 * Operazioni associate al pulsante "Invia posizione"
	 * 
	 * @param view
	 */
	public void onClickSendPos(View view){
		Location location = this.client.getLocation();
		String message = "";
		if(location != null){
			double[] latLong = {location.getLatitude(), location.getLongitude()};
			message = MessageMod.recTextMessage(latLong, location.getAccuracy(), location.getTime());
			this.client.sendMessage(
				message, this.contact.getUserName()
				);
		}else
			Toast.makeText(this, R.string.LocationWaiting, Toast.LENGTH_LONG).show();

		
	}
	
	
	/**
	 * 
	 * Operazioni associate al pulsante "Richeidi Posizione"
	 * 
	 * @param view
	 */
	public void onClickReqPos(View view){
		this.client.sendMessage(MessageMod.getSendTextMessage(), user.getText().toString());
	}


	/**
	 * 
	 * @see org.wheres2.eventmanager.PositionManager#updateLocation(android.location.Location location)
	 *  
	 */
	@Override
	public void updateLocation(Location location) {
		String myLocation = getResources().getString(R.string.MyLocation);
		Date d = new Date(location.getTime());
		SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateTimeInstance();		
		String date = sdf.format(d);
		myPosText.setText(myLocation + 
						"\nLat: " + location.getLatitude() + " Long:" + location.getLongitude() +
						"\nPrec: " + location.getAccuracy() + " Da: " + location.getProvider() + 
						"\nRilevata il: " + date);
		
	}
	
	/**
	 * 
	 * Operazioni associate al pulsante "LOCATE"
	 * 
	 * @param view
	 */
	public void onClickLocate(View view){
		Intent radarIntent = new Intent(this, Radar.class);
		radarIntent.putExtra(Radar.THROWER, Radar.CONTACT_THROWER);
		radarIntent.putExtra(Radar.CONTACT_LATITUDE, this.contact.getLocation().getLatitude());
		radarIntent.putExtra(Radar.CONTACT_LONGITUDE, this.contact.getLocation().getLongitude());
		radarIntent.putExtra(Radar.CONTACT_ACCURACY, this.contact.getLocation().getAccuracy());
		startActivity(radarIntent);
		
	}

	/**
	 * 
	 * @see  org.wheres2.eventmanager.ConnectionErrorManager#closeOnConnectionError()
	 * 
	 */
	@Override
	public void closeOnConnectionError() {
		if(this.isOnScreen)
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					close();
					
				}
			});
		else
			this.finish();
			
	}
	
	/**
	 * 
	 * Operazioni eseguite a seguito di un errore nella connessione
	 * 
	 */
	private void close(){
		
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.ConnectionErrorDialogText)
					.setTitle(R.string.ConnectionErrorDialogTitle)
					.setPositiveButton(R.string.ExitMenu, new DialogInterface.OnClickListener() {
				
						@Override
						public void onClick(DialogInterface dialog, int which) {
							client.stopLocationService();
							if (boundToService){
								unbindService(communicatorConnection);
								boundToService = false;
							}
							client.stopSelf();
							ContactInteraction.this.finish();
							dialog.dismiss();
				}
			});
			AlertDialog connectionError = builder.create();
			connectionError.show();	
			
	}
	
	
}
